<template>
  <div class="classManagement">
    <div v-if="$store.state.teacherInfomation">
      <!-- currentPage: 1, // 当前页码
      pageSize: 5, // 每页的数据条数 -->
      <el-table
        :data="
          tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
        "
        height="500"
        border
        style="width: 100%"
      >
        <el-table-column label="学校" prop="school"> </el-table-column>

        <el-table-column label="院系" prop="faculty"> </el-table-column>

        <el-table-column label="专业" prop="major">
          <template slot-scope="scope">
            <el-input
              type="text"
              v-if="scope.row.isEdit"
              v-model="scope.row.major"
            >
            </el-input>
            <span v-else>{{ scope.row.major }}</span>
          </template>
        </el-table-column>

        <el-table-column label="班级" prop="classroom">
          <template slot-scope="scope">
            <el-input
              type="text"
              v-if="scope.row.isEdit"
              v-model="scope.row.classroom"
            >
            </el-input>
            <span v-else>{{ scope.row.classroom }}</span>
          </template>
        </el-table-column>

        <el-table-column align="right">
          <template slot="header">
            <el-button size="mini" type="primary" @click="handleAdd"
              >添加</el-button
            >
          </template>

          <template slot-scope="scope">
            <el-button
              :type="scope.row.isEdit ? 'success' : 'primary'"
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
              >{{ scope.row.isEdit ? "保存" : "编辑" }}</el-button
            >
            <el-button
              :type="scope.row.isEdit ? 'default' : 'danger'"
              size="mini"
              @click="handleDelete(scope.$index, scope.row)"
              >{{ scope.row.isEdit ? "取消" : "删除" }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="block" style="margin-top: 15px">
        <el-pagination
          align="center"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[1, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.length"
        >
        </el-pagination>
      </div>
    </div>
    <div v-else>请前往个人中心完善信息 <router-link to="/teacherHome/teacherHomepage">点击前往</router-link> </div>
  </div>
</template>
<script>
import axios from "axios";
import qs from "qs";
import { Message, MessageBox } from "element-ui";
export default {
  mounted() {
    this.getClass();
  },
  data() {
    return {
      tableData: [{ cid: "", classroom: "" }],
      currentPage: 1, // 当前页码
      total: 20, // 总条数
      pageSize: 5, // 每页的数据条数
    };
  },

  methods: {
    //当选择每页条数改变时触发 选择一页显示多少行
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.currentPage = 1; //从第一页开始显示
      this.pageSize = val;
    },
    //当前页改变时触发 跳转其他页
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val;
    },

    //获取班级
    getClass() {
      axios
        .get("/v1/teachers/selectclassroom")
        .then((res) => {
          if (res.data.status == 200) {
            this.tableData = res.data.data;
            // console.log(this.tableData);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //增加班级
    addClass(row) {
      axios({
        method: "post",
        url: "/v1/teachers/addclassroom",
        data: qs.stringify({
          classroom: row.classroom,
          major: row.major,
        }),
        headers: {
          "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        },
      })
        .then((result) => {
          if (result.data.status == 200) {
            Message.success({
              showClose: true,
              message: "添加成功",
              type: "success",
            });
            //更新数据
            this.getClass();
          } else {
            Message.error({
              showClose: true,
              message: "添加失败",
              type: "error",
            });
          }
        })
        .catch((err) => {
          MessageBox("服务器开小差了~请稍后再试", "提示", {
            confirmButtonText: "确定",
            type: "error",
          });
          console.log(err);
        });
    },
    //修改班级
    updateClass(row) {
      axios({
        method: "put",
        url: "/v1/teachers/updateclassroom",
        data: qs.stringify({
          classroom: row.classroom,
          cid: row.cid,
          c_id: row.c_id, //通过这个来修改
        }),
        headers: {
          "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        },
      })
        .then((result) => {
          if (result.data.status == 200) {
            Message.success({
              showClose: true,
              message: "修改成功",
              type: "success",
            });
            //更新数据
            this.getClass();
          } else {
            Message.error({
              showClose: true,
              message: "修改失败",
              type: "error",
            });
          }
        })
        .catch((err) => {
          MessageBox("服务器开小差了~请稍后再试", "提示", {
            confirmButtonText: "确定",
            type: "error",
          });
          console.log(err);
        });
    },
    //删除班级
    deleteClass(row) {
      axios
        .delete(`/v1/teachers/deleteclassroom/${row.classroom}`)
        .then((res) => {
          if (res.data.status == 200) {
            Message.success({
              showClose: true,
              message: "删除成功",
              type: "success",
            });
            this.getClass();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //添加
    handleAdd() {
      // console.log(this.tableData)
      let obj = {
        school:this.tableData[0].school,
        faculty:this.tableData[0].faculty
      };
      
      this.tableData.unshift(obj);
      //添加编辑属性，使其一点添加就处于编辑状态
      this.$set(this.tableData[0], "isEdit", true);
      //添加标识判断是否是新增，如果是新增则在保存时发送post请求，否则发送update请求
      this.$set(this.tableData[0], "isAdd", true);
    },
    //点击编辑按钮
    handleEdit(index, row) {
      // 动态设置数据并通过这个数据判断显示方式
      if (row.isEdit) {
        // console.log("保存");
        // console.log(index, row);
        //如果是新增的
        if (row.isAdd) {
          this.addClass(row);
        } else {
          this.updateClass(row);
        }

        //点击保存时则删除isEdit
        //  this.$delete(obj,key)
        this.$delete(row, "isEdit");
      } else {
        // console.log(index, row);
        // console.log("编辑");
        //点击编辑时设置为true
        this.$set(row, "isEdit", true);
      }
    },

    //点击删除
    handleDelete(index, row) {
      if (row.isEdit) {
        // console.log("取消");
        this.$delete(row, "isEdit");
        if (row.isAdd) {
          this.tableData.shift()
        }
      } else {
        // console.log("删除");
        this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            //确定删除操作
            this.deleteClass(row);
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      }
    },
  },
};
</script>
<style lang="scss">
.classManagement {
  margin: 0 auto;
  margin-top: 50px;
}
</style>